package com.example.demo.controller;

import com.example.demo.pojo.Page;
import com.example.demo.pojo.Transaction;
import com.example.demo.pojo.User;
import com.example.demo.service.TransactionService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;

@Controller
@RequestMapping("/transaction")
public class TransactionController {

    @Autowired
    private TransactionService transactionService;

    @Autowired
    private UserService userService;

    @RequestMapping("/toAdd")
    public String toAddTrans(@RequestParam(defaultValue = "") String u_name,
                             Model model) {

        model.addAttribute("u_name", u_name);
        return "/addTransaction";
    }

    @RequestMapping("/add")
    public String addTrans(Transaction transaction, String u_name, Model model) {

        String msg;
        User user1 = userService.findUserByName(u_name);
        // foreign key
        user1.getU_transaction().add(transaction);
        transaction.setT_user(user1);
        // calculate asset
        BigDecimal asset = user1.getU_asset();
        asset = asset.add(transaction.getT_amount());
        user1.setU_asset(asset);
        transaction.setCurrentAsset(asset);
        boolean b = transactionService.addTrans(transaction);
        if (!b) {
            msg = "交易信息存在问题";
            model.addAttribute("Messages", msg);
            user1.getU_transaction().remove(transaction);
            return "redirect:/user/list";
        }
        boolean b2 = userService.editUser(user1);
        if (!b2) {
            msg = "用户信息存在问题";
            model.addAttribute("Messages", msg);
            return "redirect:/home/main";
        }
        return "redirect:/user/list?page=1";
    }

    @RequestMapping("/list")
    public String transList(@RequestParam(defaultValue = "1") Integer page, Model model) {

        Page transactions = transactionService.transAllList(page);
        model.addAttribute("transactions", transactions);
        return "/transactionAll";
    }

    @RequestMapping("/userList")
    public String transUserList(@RequestParam(defaultValue = "1") Integer page,
                                @RequestParam Integer u_id,
                                Model model) {

        Page transactions = transactionService.transUserList(u_id, page);
        model.addAttribute("transactions", transactions);
        model.addAttribute("u_id", u_id);
        return "/transaction";
    }
}
